/**
 * After ajax upload file, this script is run again, but jQuery is undefined.
 */
if ((typeof jQuery) != 'undefined' ) {
	/*
	 * This js file contains the WORKAROUND for some bugs of ExtendedDataTable.
	 */
	ExtendedDataTable.DataTable.header.prototype.OnSepMouseMove = function(event) {
		if (this.dragColumnInfo && this.dragColumnInfo.mouseDown) {
			if (!this.dragColumnInfo.dragStarted) {
				this.dragColumnInfo.dragStarted = true;
				this._showSplitter(this.dragColumnInfo.srcElement.columnIndex);
			}
			var delta = Event.pointerX(event) - this.dragColumnInfo.startX
			if (delta < this.minDelta) {
				delta = this.minDelta;
			}
			/*
			 * if (delta > this.maxDelta) { delta = this.maxDelta; }
			 */
			var x = this.dragColumnInfo.originalX + delta;
			var finalX = x - this.minColumnWidth - 6 // 6 stands for sep span
														// width;
			this.columnSplitter.moveToX(finalX);
			Event.stop(event);
		}
	};
	
	
	/**
	 * Customization: do not cache columns width to server
	 * COPIED from:
	 * 	http://fisheye.jboss.org/browse/RichFaces/branches/community/3.3.X/ui/extendedDataTable/src/main/javascript/ClientUI/controls/datatable/ExtendedDataTableHeader.js
	 * 	rev 14239
	 */	
	ExtendedDataTable.DataTable.header.prototype.OnSepMouseUp = function(event) {
		Event.stop(event);
		Event.stopObserving(document, 'mousemove', this.eventSepMouseMove);
		Event.stopObserving(document, 'mouseup', this.eventSepMouseUp);
		if (this.dragColumnInfo && this.dragColumnInfo.dragStarted) {
	
			this.dragColumnInfo.dragStarted = false;
			this.dragColumnInfo.mouseDown = false;
	
			var delta = Event.pointerX(event) - this.dragColumnInfo.startX;
			if (delta < this.minDelta) {
				delta = this.minDelta;
			}
			/* CUSTOMIZATION START ----------------------------------- */
			/*if (delta > this.maxDelta) { 
				delta = this.maxDelta; 
			}*/
			/* CUSTOMIZATION END ------------------------------------- */
			
			var columnIndex = this.dragColumnInfo.srcElement.columnIndex;
			var newWidth = this.getColumnWidth(columnIndex) + delta;
	
			this.extDt.setColumnWidth(columnIndex, newWidth);
			this.setColumnWidth(columnIndex, newWidth);
			this.extDt.updateLayout();
			if (this.extDt.onColumnResize) {
				// set properly value to this.columnWidths
				this.extDt.columnWidths = "";
				for (var i = 0; i < this.columnsNumber; i++) {
					this.extDt.columnWidths += "" + this.getColumnWidth(i) + ";";
				}// for
				this.extDt.onColumnResize(event, this.extDt.columnWidths);
			}
		}
		this._hideSplitter();
	};
	
	/**
	 * Customization: adjust the height of splitter in IE
	 * COPIED from:
	 * 	http://fisheye.jboss.org/browse/RichFaces/branches/community/3.3.X/ui/extendedDataTable/src/main/javascript/ClientUI/controls/datatable/ExtendedDataTableHeader.js
	 * 	rev 14239
	 */
	ExtendedDataTable.DataTable.header.prototype._showSplitter = function(index) {
		if(!this.columnSplitter) {
			this._createSplitter();
		}
		var pos = this.dragColumnInfo.srcElement.offsetLeft;
		pos += 6; //6 stands for width of the separatorSpan
		this.dragColumnInfo.originalX = pos;
		this.columnSplitter.show();
		/* CUSTOMIZATION START ----------------------------------- */
		var height = this.extDt.scrollingDiv.getHeight() + this.headerRow.getHeight();
		/* CUSTOMIZATION END ------------------------------------- */
		this.columnSplitter.setHeight(height);
	};
	
	ExtendedDataTable.DataTable.prototype.OnWindowResize = function() {
		// do nothing on window resize.
		if (this.table) {
			this.updateLayout();
		}
	};
	
	/**
	 * Customization: adjust the width of innerDiv to fit with mainDiv that allow vertical scroll bar.
	 * COPIED from:
	 * 	http://fisheye.jboss.org/browse/RichFaces/branches/community/3.3.X/ui/extendedDataTable/src/main/javascript/ClientUI/controls/datatable/ExtendedDataTable.js
	 * 	rev 16375
	 */
	ExtendedDataTable.DataTable.prototype.updateLayout = function() {
		ClientUILib.log(ClientUILogger.INFO, "updateLayout");
		var table = this.table.getElement();
		var outerDiv = this.outerDiv.getElement();
		var cols = this.getColumns();
		var header = this.header;
		var scrollingDiv = this.scrollingDiv;
		var mainDivHeight = this.mainDiv.getHeight();
		var mainDivWidth = this.mainDiv.getWidth();
		var headerChildren = header.getColumnCells();
		var footers = table.getElementsByTagName('tfoot');
		var footerHeight = this.getFooterHeight();
		var columnsNumber = this.getColumnsNumber();            
		var visibleHeaderWidth = this.header.getVisibleWidth();

		//var scrollbarWidth = scrollingDiv.getElement().offsetWidth - scrollingDiv.getElement().clientWidth;
		var scrollbarWidth = this.getScrollbarWidth();
		var maxAllowedWidth = mainDivWidth - scrollbarWidth;
		for (var i=0; i < columnsNumber-1; i++) {
			if (this.header.isColumnWidthPercentage(i)) {
				//change percents into pixels
				var width = this._percentsToPixels(this.header.getColumn(i).width, maxAllowedWidth);
				this.header.setColumnWidth(i, width);
				this.setColumnWidth(i, width);
			}
		}

		//var excessWidth = this.header.getVisibleWidth() - maxAllowedWidth - 1;
		//if (excessWidth > 0) {
		//    this.validateColumnsWidth(cols,excessWidth);
		//};
		
		cols[columnsNumber-1].width = null;
		cols[cols.length-1].width = null;
		
		var newHeight = mainDivHeight - header.getHeight() - footerHeight - 2;
		
		var caption = header.getCaption()
		if (caption && caption.tagName == "caption") {
			newHeight -= this.header.getCaptionHeight();
		}
		
		scrollingDiv.setStyle('height:'+ newHeight +'px;');
		this._redrawTable(table);
		header.adjustSeparators();
		this._redrawTable(this.tableB);
		this.saveRatios();
		
		/* CUSTOMIZATION START ----------------------------------- */
		var innerDiv = jQuery(outerDiv).children('.extdt-innerdiv').get(0);
		var innerHeight = innerDiv.offsetHeight;

		if (innerHeight > 0) {
			var clientHeight = innerDiv.clientHeight
			if (ClientUILib.isIE7) {
				if (jQuery(innerDiv).css('height') != (innerHeight+'px')) {
					innerHeight += 17;
					jQuery(innerDiv).css('cssText', 'width:100%; height:' + innerHeight + 'px !important;');
				}
			}
			this.outerDiv.setHeight(innerHeight);
			this.mainDiv.setHeight(innerHeight);
		}
		/* CUSTOMIZATION END ------------------------------------- */
		
		this.hideSplashScreen();
	};
	
	// Fixes a null pointer bug in IE when in a modalPanel
	ExtendedDataTable.DataTable.prototype.update = function(refreshEvents) {
		this.createControls();
		if (!ClientUILib.isIE) {
			if (this.fakeIeRow) {
				this.table.getElement().deleteRow(this.fakeIeRow.rowIndex);
				this.fakeIeRow = null;
			}
			if (this.fakeIeBodyRow) {
	
				this.tableB.deleteRow(this.fakeIeBodyRow.rowIndex);
				this.fakeIeBodyRow = null;
			}
		}
		
		if (this.selectionManager)
			this.selectionManager.refreshEvents(); // added if
		this.updateLayout();
		if (this.selectionManager)
			this.selectionManager.restoreState(); // added if
	};
	ExtendedDataTable.SelectionManager.prototype.processKeyDown = function(event) {
		if ($(this.prefix + ":n").rows.length > 0) {
			if (!event.shiftKey) {
				this.shiftRow = null;
			}
			var range, rowIndex;
			var activeRow = this.activeRow;
			var noDefault = false;
			// var arr = $(this.prefix + ":n").rows[0].id.split(":"); // ADDED
			// THIS TO FIX KEYUP IN IE NULL POINTER
			var firstRowIndex = this.dataTable.fakeIeRow ? 1 : 0;
			var arr = $(this.prefix + ":n").rows[firstRowIndex].id.split(":");
			this.firstIndex = Number(arr[arr.length - 1]);
			switch (event.keyCode || event.charCode) {
			case Event.KEY_UP:
				if (this.inFocus && activeRow != null) {
					if (this.firstIndex != activeRow) {
						rowIndex = (this.rowCount + activeRow - 1)
								% this.rowCount;
						if (!event.ctrlKey && !event.shiftKey) {
							this.selectionFlag = "x";
							range = [ rowIndex, rowIndex ];
							this.setSelection(range);
						} else if (!event.ctrlKey && event.shiftKey
								&& this.options.selectionMode == "multi") {
							if (!this.shiftRow) {
								this.shiftRow = this.activeRow;
							}
							if (this.shiftRow >= this.activeRow) {
								this.addRowToSelection(rowIndex);
							} else {
								this.removeRowFromSelection(activeRow);
							}
						}
						noDefault = true;
						this.setActiveRow(rowIndex);
					} else {
						// this.grid.getBody().showRow("up");
					}
				}
				break;
			case Event.KEY_DOWN:
				if (this.inFocus && activeRow != null) {
					rowIndex = (activeRow + 1) % this.rowCount;
					if (this.firstIndex != rowIndex) {
						if (!event.ctrlKey && !event.shiftKey) {
							this.selectionFlag = "x";
							range = [ rowIndex, rowIndex ];
							this.setSelection(range);
						} else if (!event.ctrlKey && event.shiftKey
								&& this.options.selectionMode == "multi") {
							if (!this.shiftRow) {
								this.shiftRow = this.activeRow;
							}
							if (this.shiftRow <= this.activeRow) {
								this.addRowToSelection(rowIndex);
							} else {
								this.removeRowFromSelection(activeRow);
							}
						}
						noDefault = true;
						this.setActiveRow(rowIndex);
					} else {
						// this.grid.getBody().showRow("down");
					}
				}
				break;
			case 65:
			case 97: // Ctrl-A
				if (this.inFocus && event.ctrlKey) {
					this.selectionFlag = "a";
					for ( var i = 0; i < this.rowCount; i++) {
						this.addRowToSelection(i);
					}
					noDefault = true;
				}
				break;
			case Event.KEY_TAB:
				this.lostFocus();
			}
			if (noDefault) {
				this.dataTable.showRow(this.activeRow);
				this.selectionChanged(event);
				if (event.preventBubble)
					event.preventBubble();
				Event.stop(event);
			}
		}
	};
	
	ExtendedDataTable.DataTable.prototype.destroy = function() {
        //remove listeners
		try {
			this.selectionManager.removeListeners();
		} catch (err) {
			// TDB: this error is because the the table has been removed from component tree and not rendered to client
			// so some query of richfaces return null.
			// --> just ignore it.
		}
        
		if (this.header) {
			this.header.removeListeners();
		}
        
		if (this.groupRows) {
	        var l = this.groupRows.length;
			for(var i = 0; i < l; i++) {		
				Utils.DOM.Event.removeListeners(this.groupRows[i]);
			}
		}
		
		if (this.header) {
			var headerChildren = this.header.getColumnCells();
			l = headerChildren.length;
			for (var i=0; i<l-1; i++) {
				Utils.DOM.Event.removeListeners(headerChildren[i]);
			};
		}
        
        //null all references to DOM elements
        delete this.selectionManager;
        delete this.header;
        delete this.footer;
        // START: this is what is customize
        if ($(this.id)) {
        	$(this.id).component = null;
        }
        // END: this is what is customize
        this.table = null;
        this.splashScreen = null;
		this.mainDiv = null;
		this.outerDiv = null;
		this.tableB = null;
		this.fakeIeRow = null;
		this.fakeIeBodyRow = null;
		this.cols = null;
		this.scrollingDiv = null;
		this.groupRows = null;
		this.groups = null;
		Event.stopObserving(window, 'resize', this.eventContainerResize);
	};
}